<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               :before-close="handleClose"
               title="新增/编辑站点"
               ref="drawer"
               size="700px">
      <!-- 主体信息 -->
      <div class="ele-body">
        <el-card shadow="never">
          <el-form label-position="top"
                   :model="form"
                   ref="form"
                   :rules="rules"
                   class="ruleForm">
            <el-form-item label="站点名称"
                          prop="siteName">
              <el-input maxlength="20"
                        show-word-limit
                        placeholder="请输入站点名称"
                        v-model.trim="form.siteName"></el-input>
            </el-form-item>
            <el-form-item label="站点域名"
                          prop="siteDomainName">
              <el-input show-word-limit
                        placeholder="请输入站点域名"
                        v-model.trim="form.siteDomainName"></el-input>
              <span class="agy">注意:【域名不加http//或https//开头,例如yjyksaas.adsdsdin16sdj.com】</span>
            </el-form-item>
            <el-form-item label="联系人"
                          prop="contactPerson">
              <el-input maxlength="20"
                        show-word-limit
                        placeholder="请输入联系人"
                        v-model.trim="form.contactPerson"></el-input>
            </el-form-item>
            <el-form-item label="账号"
                          prop="account">
              <el-input maxlength="25"
                        show-word-limit
                        :disabled="isUpdate ? true : false"
                        placeholder="请输入账号"
                        v-model.trim="form.account"></el-input>
            </el-form-item>
            <el-form-item v-show="hiddenPassword"
                          label="密码"
                          prop="password">
              <el-input maxlength="25"
                        show-password
                        show-word-limit
                        placeholder="请输入密码"
                        v-model.number="form.password"></el-input>
            </el-form-item>
            <el-form-item label="联系电话"
                          prop="contactNumber">
              <el-input maxlength="11"
                        show-word-limit
                        placeholder="请输入联系电话"
                        v-model.number="form.contactNumber"></el-input>
            </el-form-item>

            <el-form-item label="到期时间:"
                          prop="dateRange">
              <el-date-picker v-model="form.timeValue"
                              type="date"
                              placeholder="选择日期时间">
              </el-date-picker>
              <!-- <el-date-picker v-model="form.dateRange"
                              type="datetime"
                              placeholder="选择日期时间"
                              class="ele-fluid" /> -->
            </el-form-item>

            <el-form-item label="上传图片:"
                          prop="logo">
              <!-- 提交图片 -->
              <el-upload action="#"
                         :on-exceed="exceedFn"
                         list-type="picture-card"
                         :file-list="fileList"
                         :limit="1"
                         :on-change="
                  (files, fileList) => handleFileChange(files, fileList)
                "
                         :auto-upload="false">
                <i slot="default"
                   class="el-icon-plus"></i>
                <div slot="file"
                     slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail"
                       :src="file.url"
                       alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview()">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </el-form-item>

            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">提交</el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>
<script>
import { storageConfigDetail } from '@/api/storageInfo/index';
import { getToken } from '@/utils/token-util';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import {
  userOssSignature,
  qnyOssSignature
} from '@/api/creatCenter/material';
import { siteInsert, siteModify } from '@/api/siteList/index';

import axios from 'axios';
export default {
  name: 'drawerEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },

  data () {
    // const logo = (rule, value, callback) => {
    //   console.log(this.form.logo);
    //   if (!this.form.logo) {
    //     callback(new Error('请上传图片'));
    //   } else {
    //     callback();
    //   }
    // };
    // 默认表单数据
    const defaultWhere = {
      // 站点名称
      siteName: '',
      // 站点域名
      siteDomainName: '',
      // 联系人
      contactPerson: '',
      // 联系电话
      contactNumber: '',
      //   账户
      account: '',
      //   密码
      password: '',
      // 申请时间
      timeValue: '',
      logo: ''
    };

    return {
      isUpdate: false,
      dialogVisible: false,
      viewerVisible: false,
      form: {
        ...defaultWhere
      },
      imgViewArr: [],
      loading: false,
      //  图片回显
      fileList: [],
      sumbitForm: {},
      dialogImageUrl: '',
      imageUrl: '',
      hiddenPassword: true,

      storageMode: '',
      // 正则校验
      rules: {
        siteName: [
          {
            required: true,
            message: '请输入站点名称',
            trigger: 'blur'
          }
        ],
        siteDomainName: [
          {
            required: true,
            message: '请输入站点域名',
            trigger: 'blur'
          }
        ],
        contactPerson: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }
        ],
        account: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        contactNumber: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        // logo: [{ required: true, validator: logo, trigger: 'change' }]
      }
    };
  },
  created () {
    this.storageConfig();
  },
  computed: {
    // 营业执照
    urlListArray () {
      return this.imgViewArr;
    },
    // ** 隐私部分带*号
    hiddenCardId () {
      return function (str, frontLen = 4, endLen = 4) {
        //str：要进行隐藏的变量  frontLen: 前面需要保留几位    endLen: 后面需要保留几位
        var len = str.length - frontLen - endLen;
        var start = '';
        for (var i = 0; i < len; i++) {
          start += '*';
        }
        // 最后的返回值由三部分组成
        return (
          str.substring(0, frontLen) +
          start +
          str.substring(str.length - endLen)
        );
      };
    },
    //  code码获取城市标题
    getRegionLabel () {
      return function (params) {
        console.log(cityData);
        return getRegionLabel(params);
      };
    }
  },
  methods: {
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.logo = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 获取存储配置
    async storageConfig () {
      const res = await storageConfigDetail();

      //   console.log(res.storageMode);

      this.storageMode = res?.storageMode;
    },
    // 关闭抽屉
    handleClose () {
      this.$confirm('确认关闭？')
        .then(_ => {
          console.log('查看详情');
          this.$emit('update:drawerEditBoolen', false);
        })
        .catch(_ => { });

    },
    async handleFileChange (file, fileList) {
      if (this.storageMode == 2) {
        this.aliFn(file, fileList);
      } else if (this.storageMode == 3) {
        this.qnyFn(file, fileList);
      }
    },

    // 阿里云
    async aliFn (file, fileList) {
      console.log(file);
      this.loading = true;
      const res = await userOssSignature();
      let files = file.raw;
      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', date + suffix);
      param.append('policy', res.policy);
      param.append('OSSAccessKeyId', res.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', res.signature);
      param.append('file', files, files.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);

      let result = await axios.post(res.host, param, config);
      let url = res.host + '/' + date + suffix;
      console.log(url);
      this.form.logo = url;
      this.imageUrl = url;
      this.loading = false;
    },
    async qnyFn (file, fileList) {
      this.loading = true;
      console.log(file, fileList);

      let files = file.raw;
      console.log(files);
      //   // 构建请求参数
      let param = new FormData();

      param.append('file', files, files.name);
      param.append('getsize', files.size);
      param.append('getContentType', files.type);
      param.append('getoriginalfilename', files.name);
      param.append('getName', files.name);

      const res = await qnyOssSignature(param);
      console.log(res.url);
      this.imageUrl = res.url;
      this.form.logo = res.url;
      console.log('上传图片成功=======', res);
      this.loading = false;
    },

    // 新增
    save () {
      this.$refs['form'].validate((valid) => {
        console.log('保存提交');
        if (!valid) {
          return false;
        }
        this.loading = true;
        for (const key in this.form) {
          if (key == 'timeValue') {
            console.log(this.form[key]);

            // let startTime = this.form[key]?.[0];
            let endTime = this.form[key];
            // this.sumbitForm['startDate'] =
            //   startTime == undefined ? '' : startTime;
            this.sumbitForm['endDate'] = endTime == undefined ? '' : endTime;
          } else {
            this.sumbitForm[key] = this.form[key];
          }
        }
        this.sumbitForm.logo = this.imageUrl;
        console.log(this.sumbitForm);
        if (this.isUpdate) {
          this.sumbitForm.password = null;
        }
        const saveOrUpdate = this.isUpdate ? siteModify : siteInsert;
        saveOrUpdate(this.sumbitForm)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);
            if (!this.isUpdate) {
              this.$router.go(0);
            }
            this.$emit('update:drawerEditBoolen', false);
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.$util);
          if (this.data) {
            // 隐藏账号密码

            this.hiddenPassword = false;
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });

            if (this.form.logo) {
              this.imageUrl = this.form.logo;
              let markIndex = this.form.logo.lastIndexOf('.');
              let suffix = this.form.logo.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.logo
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.logo
                  }
                ];
              }
            } else {
              this.fileList = [];
            }

            this.form.dateRange = [this.data.startDate, this.data.endDate];
            this.form.timeValue = this.data.endDate;
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
            this.hiddenPassword = true;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
            this.fileList = [];
          });
        }
      });
    }
  }
};
</script>
<style lang="less">
.agy {
  color: #b5b5b7 !important;
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
}

// /deep/.el-select {
//   width: 100%;
// }
// /deep/.el-cascader--medium {
//   width: 100%;
// }
</style>
